package cn.sdormitory.controller.smartdor;

import cn.sdormitory.common.api.CommonPage;
import cn.sdormitory.common.api.CommonResult;
import cn.sdormitory.common.utils.poi.ExcelPoi;
import cn.sdormitory.report.vo.AttenceStatisticsVO;
import cn.sdormitory.smartdor.dto.SdRentExportDTO;
import cn.sdormitory.smartdor.dto.SdRentImportDTO;
import cn.sdormitory.smartdor.service.SdRentService;
import cn.sdormitory.smartdor.vo.req.SdRentFormVo;
import cn.sdormitory.smartdor.vo.req.SdRentQueryParam;
import cn.sdormitory.smartdor.vo.resp.SdRentVO;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/smartdor/rent")
public class SdRentController {

    @Autowired
    SdRentService sdRentService;


    @GetMapping("/sync/sdSentData")
    public CommonResult syncStudentData(){
        return sdRentService.syncStudentData();
    }

    @PostMapping("/renew")
    public CommonResult renew(@RequestBody SdRentFormVo vo) throws Exception{
        return sdRentService.renew(vo);
    }

    @PostMapping("/find/sdRentPageList")
    public CommonResult<CommonPage<SdRentVO>> findSdRentPageList(@RequestBody SdRentQueryParam queryParam){
        IPage<SdRentVO> pageList = sdRentService.findSdRentPageList(queryParam);
        return CommonResult.success(CommonPage.restPage(pageList));
    }

    @PostMapping("/import/sdSentData")
    public CommonResult importSdSentData(@RequestParam(value = "upload") MultipartFile upload) throws Exception{
        try{
            if(upload == null || upload.getSize() == 0){
                return CommonResult.failed("文件为空!!!");
            }
            List<SdRentImportDTO> sdRentDTOList = new ExcelPoi<SdRentImportDTO>().importObjectList(upload.getInputStream(), upload.getOriginalFilename(), SdRentImportDTO.class);
            List<String> list = sdRentService.importSdSentData(sdRentDTOList);
            return CommonResult.success(list);
        } catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed("信息导入失败!!!");
        }
    }

    @PostMapping("/export")
    public CommonResult exportSdRent(HttpServletResponse response, @RequestBody SdRentQueryParam queryParam){
        List<SdRentExportDTO> exportList = sdRentService.findSdRentExportList(queryParam);
        try {
            EasyExcel.write(response.getOutputStream(), SdRentExportDTO.class).sheet("缴费名单").doWrite(exportList);
            return CommonResult.success();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return CommonResult.failed();
    }
}
